<template>
  <div class="outer-container">
    <h3>委外到货单</h3>
    <el-form :model="formData" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="单据编码">
            <el-input v-model="formData.documentCode"  disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="业务类型">
            <el-select v-model="formData.businessType" placeholder="请选择业务类型">
              <el-option label="委外到货" value="委外到货"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="委外单号">
            <el-input v-model="formData.outsourcingOrderNumber" placeholder="请选择委外单号" disabled>
              <template #append>
                <el-button @click="selectOutsourcingOrder()">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="单据日期">
            <el-date-picker v-model="formData.documentDate" type="date" placeholder="选择单据日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="操作员">
            <el-input v-model="formData.operator" placeholder="操作员" :value="formData.operator || 'njsun'" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商">
            <el-input v-model="formData.supplier" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="单据状态">
            <el-input v-model="formData.documentStatus" placeholder="单据状态" :value="formData.documentStatus || '开立'" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核员">
            <el-input v-model="formData.auditor" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划单号">
            <el-input v-model="formData.planOrderNumber"  disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="业务状态">
            <el-select v-model="formData.businessStatus" placeholder="请选择业务状态">
              <el-option label="正常" value="正常"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核日期">
            <el-date-picker v-model="formData.auditDate" type="date"  disabled></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="跟单编号">
            <el-input v-model="formData.followOrderNumber"  disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="物料编码">
            <el-input v-model="formData.materialCode"  disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料名称">
            <el-input v-model="formData.materialName"  disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="到货数量">
            <el-input v-model="formData.arrivalQuantity" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="备注信息">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注信息"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入库仓库">
            <el-select v-model="formData.warehouse" placeholder="请选择入库仓库">
              <el-option label="成品仓" value="成品仓"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 选择委外单号 -->
    <el-dialog v-model="dialogTableVisible" title="选择委外订单" width="1200">
    <div class="search-bar">
      <el-input placeholder="跟单编号" v-model="searchParams.documentCode" style="width:150px;margin-right: 15px;"></el-input>
      <el-input placeholder="供应商" v-model="searchParams.supplier" style="width:150px;margin-right: 15px;"></el-input>
      <el-input placeholder="物料名称" v-model="searchParams.materialName" style="width:150px;margin-right: 15px;"></el-input>
      <el-date-picker
        v-model="searchParams.startDate"
        type="date"
        placeholder="开始日期"
        style="width: 120px;"
      ></el-date-picker>
      <el-date-picker
        v-model="searchParams.endDate"
        type="date"
        placeholder="结束日期"
        style="width: 120px;margin-right: 20px;"
      ></el-date-picker>
      <el-button type="primary" @click="search" style="margin-right: 20px;">搜索</el-button>
      <el-button type="primary" @click="resetSearch">查看所有</el-button>
    </div>
    <el-table :data="gridData" @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column property="documentCode" label="跟单编号" width="150" />
      <el-table-column property="supplier" label="供应商" width="150" />
      <el-table-column property="materialName" label="物料名称" width="150" />
      <el-table-column property="materialCode" label="物料编码" width="150" />
      <el-table-column property="outsourcingQuantity" label="委外数量" width="100" />
      <el-table-column property="documentDate" label="单据日期" width="150" />
      <el-table-column property="documentStatus" label="单据状态" width="100" />
      <el-table-column property="businessStatus" label="业务状态" width="100" />
    </el-table>
    <div class="pagination">
      <el-pagination
      v-model:current-page="currentPage4"
      v-model:page-size="pageSize4"
      :page-sizes="[15, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="6"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    />
    </div>
    <div class="action-buttons">
      <el-button type="primary" @click="selectOrder">确定</el-button>
      <el-button @click="dialogTableVisible = false">取消</el-button>
    </div>
  </el-dialog>

    <div class="button-container">
      <el-button type="primary" @click="AdddOutSourArrlav()">保存</el-button>
      <el-button @click="cancelData()">取消</el-button>
      <el-button type="success" @click="approveData">审核</el-button>
      <el-button type="warning" @click="rejectApproveData">反审核</el-button>
      <el-button @click="collapseData">收起</el-button>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { ElTable } from 'element-plus';
import { saveAs } from 'file-saver';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from "@/stores/counter";
import { KongaUrl } from '@/axios/axiosHelp';
import { Search } from '@element-plus/icons-vue'

const Store = useCounterStore()
const router=useRouter();
const route=useRoute();
const formData=reactive({
  pid:route.query.id,
 "documentCode": `WWDH${Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000}`,
  "businessType": route.query.businessType,
  "outsourcingOrderNumber": route.query.documentCode,
  "materialCode": route.query.materialCode,
  "remark": route.query.remark,
  "documentDate": new Date(),
  "operator": Store.user.userName,
  "supplier": route.query.supplier,
  "materialName": route.query.materialName,
  "documentStatus": route.query.documentStatus,
  "auditor": route.query.auditor,
  "planOrderNumber": route.query.planOrderNumber,
  "arrivalQuantity":  route.query.outsourcingQuantity,
  "businessStatus": route.query.businessStatus,
  "auditDate": null,
  "followOrderNumber": route.query.documentCode,
  "warehouse": route.query.warehouse,
  "createdAt": new Date(),
  "createdBy": Store.user.userName,
  "lastModifiedAt": null,
  "lastModifiedBy":'',
  "isDelete": 0,
  "orderDeliveryDate": route.query.orderDeliveryDate
})

const AdddOutSourArrlav=()=>{
  console.log(formData);
  KongaUrl({
    url:'/weiwaixie/api/Outsour/AddoutSourArrival',
    method:'post',
    data:formData
  })
  .then(res=>{
    if(res.data.code==101){
      ElMessage.success("操作成功");
      router.push("/OutsourceddeliveryShow")
    }
  })
}

const cancelData=()=>{
  router.push("/OutsourceddeliveryShow")
}
const approveData = () => {
  // 审核逻辑，例如发送审核请求到后端
  console.log('审核操作', formData)
}

const rejectApproveData = () => {
  // 反审核逻辑，例如发送反审核请求到后端
  console.log('反审核操作', formData)
}

const collapseData = () => {
  // 收起逻辑，例如隐藏部分内容
  console.log('收起操作')
}
const dialogTableVisible = ref(false)
const gridData=ref([]);
const searchParams = reactive({
  documentCode: '',
  supplier: '',
  materialName: '',
  startDate: '',
  endDate: ''
})

const search = () => {
  // 实现搜索逻辑
  KongaUrl({
    url: '/weiwaidu/api/OutSourc/QueryOutSourOrder',
    method: 'get',
    params: {
      pageindex: currentPage4.value,
      pagesize: pageSize4.value,
      documentCode: searchParams.documentCode,
      supplier: searchParams.supplier,
      materialName: searchParams.materialName,
      startDate: searchParams.startDate,
      endDate: searchParams.endDate
    }
  }).then(res => {
    if (res.data.code == 101) {
      gridData.value = res.data.list;
    }
  })
}

const resetSearch = () => {
  searchParams.documentCode = '';
  searchParams.supplier = '';
  searchParams.materialName = '';
  searchParams.startDate = '';
  searchParams.endDate = '';
  search();
}

const handleSelectionChange = (val) => {
  if (val.length > 1) {
    ElMessage.warning('请选择单条委外订单数据')
    return
  }
  selectedOrder.value = val[0] || null
}

const selectOrder = () => {
  if (!selectedOrder.value) {
    ElMessage.warning('请先选择委外订单')
    return
  }
  // 回填委外到货单数据
  formData.outsourcingOrderNumber = selectedOrder.value.documentCode;
  formData.supplier = selectedOrder.value.supplier;
  formData.materialCode = selectedOrder.value.materialCode;
  formData.materialName = selectedOrder.value.materialName;
  formData.planOrderNumber = selectedOrder.value.planOrderNumber;
  formData.followOrderNumber = selectedOrder.value.documentCode;
  formData.orderDeliveryDate = selectedOrder.value.orderDeliveryDate;
  formData.documentStatus = '开立';
  formData.businessStatus = '正常';
  formData.operator = Store.user.userName;
  formData.documentDate = new Date();
  // 自动回填数量
  formData.arrivalQuantity = selectedOrder.value.outsourcingQuantity;
  
  dialogTableVisible.value = false;
}

const selectedOrder = ref(null);
const currentPage4 = ref(1);
const pageSize4 = ref(15);
const handleSizeChange = (newSize) => {
  pageSize4.value = newSize;
  search();
}
const handleCurrentChange = (newPage) => {
  currentPage4.value = newPage;
  search();
}

const selectOutsourcingOrder = () => {
  // 委外单号选择逻辑，例如弹出选择框
  KongaUrl({
    url:'/weiwaidu/api/OutSourc/QueryOutSourOrder',
    method:'get',
    params:{
      pageindex:1,
      pagesize:100
    }
  })
  .then(res=>{
    if(res.data.code==101){
      gridData.value=res.data.list;
      console.log(gridData.value);
      dialogTableVisible.value=true;
    }
  })

  console.log('选择委外单号操作')
}
</script>

<style scoped>
.outer-container {
  padding: 20px;
}
.button-container {
  margin-top: 20px;
  text-align: right;
}
</style>